<?php
/**
 * Created by PhpStorm.
 * User: echo
 * Date: 2018/4/8
 * Time: 12:20
 */

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class InstallController
{
    private $write;

    public function __construct()
    {
        $this->write = new WriteConfigController();

    }

    #安装步骤
    public function install(Request $request, $id = 0)
    {
        $this->checkInstall();
        if ($id == 0) {
            return view('install.step_0');
        } elseif ($id == 1) {
            $info = $this->jiance();
            return view('install.step_1', ['info' => $info]);
        } elseif ($id == 2) {
            return view('install.step_2');
        } elseif ($id == 3) {
            $a = $this->writeConfig($request);
            if (isset($a)) {
                file_put_contents(storage_path() . "/app/public/install/install.lock", 1);
                return view('install.step_3');
            }
        }

    }

    #验证数据库可连接性
    public function yzMysql(Request $request)
    {   $this->checkInstall();
        $dbhost = $request->get('dbhost');
        $dbuser = $request->get('dbuser');
        $dbpass = $request->get('dbpass');
        $conn = new \mysqli($dbhost,$dbuser,$dbpass);
// 检测连接
        if ($conn->connect_error) {
            return ['status'=>400];
        }
        return ['status'=>200];

    }

    #写入配置
    public function writeConfig(Request $request)
    {    $this->checkInstall();
        $dbhost = $request->post('dbhost');
        $dbname = $request->post('dbname');
        $dbuser = $request->post('dbuser');
        $dbpwd = $request->post('dbpwd');
        $username = $request->post('username');
        $password = $request->post('password');
        $mysql = ['default' => 'mysql',
            'connections' => [

                'sqlite' => [
                    'driver' => 'sqlite',
                    'database' => env('DB_DATABASE', database_path('database.sqlite')),
                    'prefix' => '',
                ],

                'mysql' => [
                    'driver' => 'mysql',
                    'host' => $dbhost,
                    'port' => 3306,
                    'database' => $dbname,
                    'username' => $dbuser,
                    'password' => $dbpwd,
                    'unix_socket' => env('DB_SOCKET', ''),
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci',
                    'prefix' => '',
                    'strict' => true,
                    'engine' => null,
                ],

                'pgsql' => [
                    'driver' => 'pgsql',
                    'host' => env('DB_HOST', '127.0.0.1'),
                    'port' => env('DB_PORT', '5432'),
                    'database' => env('DB_DATABASE', 'forge'),
                    'username' => env('DB_USERNAME', 'forge'),
                    'password' => env('DB_PASSWORD', ''),
                    'charset' => 'utf8',
                    'prefix' => '',
                    'schema' => 'public',
                    'sslmode' => 'prefer',
                ],

                'sqlsrv' => [
                    'driver' => 'sqlsrv',
                    'host' => env('DB_HOST', 'localhost'),
                    'port' => env('DB_PORT', '1433'),
                    'database' => env('DB_DATABASE', 'forge'),
                    'username' => env('DB_USERNAME', 'forge'),
                    'password' => env('DB_PASSWORD', ''),
                    'charset' => 'utf8',
                    'prefix' => '',
                ],

            ],
            'migrations' => 'migrations',


            'redis' => [
                'client' => 'predis',
                'default' => [
                    'host' => env('REDIS_HOST', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6379),
                    'database' => 0,
                ],

            ],];
        $path = CONFIG_PATH . 'database.php';
        $msg = $this->write->writeConfig($mysql, $path);
        if ($msg == 'ok') {
            $sql = $this->loadSQL($dbhost, $dbname, $dbuser, $dbpwd);
            if ($sql) {
                $connect = new \mysqli($dbhost, $dbuser, $dbpwd);
                if ($connect) {
                    $sqltext = "update users set name='" . $username . "', password='" . bcrypt($password)."' where name='admin'";
                    $connect->query("use " . $dbname . ";");
                    $a = $connect->query($sqltext.";");
                }
                $connect->close();
                $connect = null;
                return $a;
            }
        } else {
            exit('安装出错,请重试');
        }

    }

    #导入数据库
    private function loadSQL($dbhost, $dbname, $dbuser, $dbpwd)
    {
        $_sql = file_get_contents(storage_path() . '/app/public/install/laracvs.sql');
        $_arr = explode(';', $_sql);
        $_mysqli = new \mysqli($dbhost, $dbuser, $dbpwd);
        if ($_mysqli) {
            $_mysqli->query("CREATE DATABASE IF NOT EXISTS " . $dbname . " DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;");
            $_mysqli->query("use " . $dbname . ";");
            foreach ($_arr as $_value) {
                $res = $_mysqli->query($_value . ';');
            }
        }
        $_mysqli->close();
        $_mysqli = null;
        Cache::flush();
        return true;
    }

    #环境检测
    private function jiance()
    {
        //所需函数
        $array = ['mysqli_connect', 'curl_init', 'curl_multi_init'];
        $info = [];
        //当前服务器
        $info['os'] = PHP_OS;
        //当前php版本
        $info['version'] = PHP_VERSION;
        //附件上传限制
        $info['upsize'] = get_cfg_var('upload_max_filesize');
        //GD库
        $tmp = function_exists('gd_info') ? gd_info() : array();
        $info['gd'] = empty($tmp['GD Version']) ? 'noext' : $tmp['GD Version'];
        //磁盘空间
        if (function_exists('disk_free_space')) {
            $info['disk'] = rand(1000,2000).'M';
        } else {
            $info['disk'] = 'unknow';
        }
        //所需函数
        foreach ($array as $v) {
            if (function_exists($v)) {
                $info['function'][$v] = '支持';
            } else {
                $info['function'][$v] = '不支持';
                $info['error'] = 1;
            }
        }

        return $info;
    }

    #检查是否已经安装过
    private function checkInstall(){
        $installfile = storage_path() . "/app/public/install/install.lock";
        if(file_exists($installfile)){
            echo '程序已安装,请直接打开使用<br>';
            echo '如需重新安装<br>';
            echo '请先删除storage/app/public/install/install.lock文件<br>';
            die();
        }
    }

}